package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.itheima.mapper.MemberMapper;
import com.itheima.pojo.Member;
import com.itheima.service.MemberService;
import com.itheima.utils.MD5Utils;
import org.springframework.beans.factory.annotation.Autowired;

import java.text.SimpleDateFormat;
import java.util.*;

@Service(interfaceClass = MemberService.class)
public class MemberServiceImpl implements MemberService {

    @Autowired
    private MemberMapper memberMapper;

    @Override
    public Member findByTelephone(String telephone) {
        return memberMapper.findByTelephone(telephone);
    }

    @Override
    public void add(Member member) {

        if (member.getPassword() != null) {
            member.setPassword(MD5Utils.md5(member.getPassword()));
        }

        memberMapper.add(member);
    }

    @Override
    public Map getMemberReport() {

        Calendar calendar = Calendar.getInstance();
        calendar.add(calendar.MONTH,-12);

        List<String> months = new ArrayList<>();
        List<Integer> memberCounts = new ArrayList<>();

        for (int i = 0; i < 12; i++) {
            Date time = calendar.getTime();
            String month = new SimpleDateFormat("yyyy-MM").format(time);

            String monthBegin = month + "-1";
            String monthEnd = month + "-31";

            Integer count = memberMapper.findMemberCountByMonth(monthBegin, monthEnd);

            months.add(month);
            memberCounts.add(count);

            calendar.add(calendar.MONTH, 1);
        }

        HashMap<String, List> map = new HashMap<>();
        map.put("months", months);
        map.put("memberCounts", memberCounts);

        return map;
    }
}
